package com.liuwenlin.zookeeper.zkclient.config;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 在zookeeper连接建立完成后再返回zookeeper实例
 * @author liuwenlin
 * @version v1.0
 * @date 2021/2/1 16:34
 */
public class ZKUtils {

    private static ZooKeeper zooKeeper;

    private static String address = "hadoop.master.com:2181,hadoop.slave1.com:2181,hadoop.slave2.com:2181";

    private static DefaultWatch watcher = new DefaultWatch();

    private static CountDownLatch latch = new CountDownLatch(1);

    public static ZooKeeper getZooKeeper(){

        try {
            zooKeeper = new ZooKeeper(address, 3000, watcher);
            watcher.setCc(latch);
            latch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return zooKeeper;
    }

    /**
     * 传入项目使用的根目录进行返回zookeeper实例
     * @param rootPath
     * @return
     */
    public static ZooKeeper getZooKeeperWithRootPath(String rootPath){

        //判断目录是否以 / 开始的
        if(!rootPath.startsWith("/")){
            rootPath = "/" + rootPath;
        }

        try {
            zooKeeper = new ZooKeeper(address + rootPath, 3000, watcher);
            watcher.setCc(latch);
            latch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return zooKeeper;
    }

}
